package com.cx.mall.search.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cx.mall.common.entity.goods.model.Product;
import com.cx.mall.common.entity.search.SkuEs;
import com.cx.mall.common.util.ResponseVo;
import com.cx.mall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.data.elasticsearch.NoSuchIndexException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/search/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public ResponseVo search(Product product) {
        try {
            log.info("开始搜索商品，参数: {}", product);
            IPage<SkuEs> page = productService.search(product);
            log.info("搜索成功，返回结果数量: {}", page.getTotal());
            return ResponseVo.success(page);
        } catch (DataAccessResourceFailureException e) {
            log.error("Elasticsearch连接失败: {}", e.getMessage(), e);
            return ResponseVo.fail("搜索服务暂时不可用，请稍后重试");
        } catch (NoSuchIndexException e) {
            log.error("索引不存在: {}", e.getMessage(), e);
            return ResponseVo.fail("搜索索引不存在，请联系管理员");
        } catch (RuntimeException e) {
            log.error("Elasticsearch搜索异常: {}", e.getMessage(), e);
            return ResponseVo.fail("搜索服务异常，请稍后重试");
        } catch (Exception e) {
            log.error("搜索服务未知异常: {}", e.getMessage(), e);
            return ResponseVo.fail("搜索服务异常，请联系管理员");
        }
    }
}
